<template>
<view>
<!--pages/tools/wangdian/souvenir/souvenir.wxml-->

<map id="map" :longitude="t_lng" :latitude="t_lat" :scale="tabs[xmwzB_index].scale" :markers="markers" class="map_map" style="width: 100%;" @callouttap="callouttap">
</map>
<scroll-view class="body" :scroll-y="true">
	<block v-if="arrlist[xmwzB_index].length>1">
		<block v-for="(item, index) in arrlist[xmwzB_index]" :key="index">
			<block v-if="index>0">
				<view class="box row row-between">
					<view class="left">
						<view class="tit">
							{{item.title}}
						</view>
						<view class="intro">
							{{item.distance}} | {{item.address}}
						</view>
					</view>
					<view class="right" :data-latitude="item.latitude" :data-longitude="item.longitude" :data-name="item.title" :data-address="item.address" @tap="nav">
						<image src="/static/images/around/navigation_btn.png"></image>
					</view>
				</view>
				<view class="fgx"></view>
			</block>
		</block>
	</block>
	<block v-else>
		<view style="text-align:center;padding-top:120rpx;">没有找到附近的{{tabs[xmwzB_index].name}}哦~</view>
	</block>
</scroll-view>
<!-- tab点击切换不同内容 -->
<cover-view class="xmwzB flex tfAlignC flexSb">
	<cover-view v-for="(item, index) in tabs" :key="index" :class="'xmwzBLi ' + (index==xmwzB_index?'on':'')" :data-index="index" @tap.stop="xmwzB_click">
		{{item.name}}
		<cover-view :class="index==xmwzB_index?'online':''"></cover-view>
	</cover-view>
</cover-view>

<!-- 导航图标，点击跳转导航 -->
<cover-image class="navigation_btn" src="/static/images/around/navigation_btn.png" @tap="show_big_map" :hidden="!navigation"></cover-image>
</view>
</template>

<script>
var QQMapWX = require("../../../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js");
var qqmapsdk = new QQMapWX({
  key: 'KR7BZ-XSQ3P-VGFD7-LNRZL-E7PXE-STF76'
});
const util = require("../../../../utils/util.js");

export default {
  data() {
    return {
      // 获取的经纬度
      t_lat: '',
      t_lng: '',
      // 地图的markers
      markers: [],
      // 当前选中第几个
      xmwzB_index: 0,
      // tab列表
      tabs: [{
        name: '机场',
        scale: 16
      }, {
        name: '码头',
        scale: 16
      }, {
        name: '汽车站',
        scale: 16
      }, {
        name: '地铁站',
        scale: 16
      }, {
        name: '火车站',
        scale: 16
      }],
      // 把从腾讯地图SDK获取的位置存起来，以后每次点击就不用请求了。
      arrlist: [[], [], [], [], []],
      // 记录当前地图选中的icon点
      location: ['', '', '', '', ''],
      // 是否展示地图跳转导航按钮
      navigation: false,
      scaleArr: []
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    uni.getLocation({
      type: 'gcj02',
      //返回可以用于wx.openLocation的经纬度
      success: res => {
        const latitude = res.latitude;
        const longitude = res.longitude;
        var that = this;
        that.setData({
          t_lat: latitude,
          t_lng: longitude
        });
        var marks = []; // 地图上的icon图标

        marks.push({
          // 获取返回结果，放到mks数组中
          latitude,
          longitude,
          iconPath: "/static/images/around/address.png",
          //图标路径
          width: 20,
          height: 20,
          zIndex: 999,
          callout: {
            display: 'ALWAYS'
          }
        }); // 地图上的气泡点

        that.setData({
          markers: marks
        });

        if (options.name) {
          let index = that.tabs.findIndex(item => {
            return item.name == options.name;
          });
          that.setData({
            xmwzB_index: index
          }, () => {
            that.nearby_search(that.tabs[index].name);
          });
        } else {
          // 进页面先请求一波(第一个tab下对应的列表内容)
          that.nearby_search(that.tabs[0].name);
        }
      }
    });
  },
  methods: {
    // 点击tab切换
    xmwzB_click(e) {
      var that = this;
      var index = e.currentTarget.dataset.index;
      that.setData({
        xmwzB_index: index
      }, () => {
        var name = that.tabs[index].name;
        that.nearby_search(name);
      });
    },

    // 通过关键字调用地图SDK，搜索获取结果列表
    nearby_search(key) {
      var that = this;
      var xmwzB_index = that.xmwzB_index;
      var list_c = that.arrlist[xmwzB_index]; // 判断是否请求过了，如果没请求过则请求；请求过了就直接赋值

      if (list_c && list_c.length) {
        that.setData({
          markers: list_c
        });
      } else {
        uni.showToast({
          title: '请稍后',
          icon: 'loading',
          duration: 2000
        });
        qqmapsdk.search({
          keyword: key,
          // 搜索关键词
          page_size: 5,
          // 一页展示几个
          location: that.t_lat + ',' + that.t_lng,
          //设置周边搜索中心点
          success: function (res) {
            //搜索成功后的回调
            uni.hideToast({});
            var marks = [];
            marks.push({
              // 获取返回结果，放到mks数组中
              latitude: that.t_lat,
              longitude: that.t_lng,
              iconPath: "/static/images/around/address.png",
              //图标路径
              width: 20,
              height: 20,
              zIndex: 999,
              callout: {
                display: 'ALWAYS'
              }
            });

            if (!res.data.length) {
              uni.showToast({
                title: '没有找到附近的' + that.tabs[that.xmwzB_index].name,
                icon: 'none',
                duration: 2000
              });
              return;
            }

            for (var i = 0; i < res.data.length; i++) {
              let distance = that.getDistance(res.data[i].location.lng, res.data[i].location.lat, that.t_lng, that.t_lat);
              distance = distance < 1 ? `${(parseFloat(distance) * 1000).toFixed(0)}米` : `${parseFloat(distance).toFixed(2)}公里`;
              marks.push({
                // 获取返回结果，放到mks数组中
                title: res.data[i].title,
                id: res.data[i].id,
                latitude: res.data[i].location.lat,
                longitude: res.data[i].location.lng,
                iconPath: "/static/images/around/cover_1.png",
                //图标路径
                width: 20,
                height: 20,
                address: res.data[i].address,
                distance,
                callout: {
                  content: res.data[i].title,
                  color: '#404040',
                  bgColor: '#ffffff',
                  borderWidth: 1,
                  borderColor: '#8a8a8a',
                  fontSize: 14,
                  padding: 10,
                  borderRadius: 10,
                  display: 'ALWAYS'
                }
              }); // 根据距离决定缩放

              if (i == res.data.length - 1) {
                const maxDistance = that.getDistance(res.data[res.data.length - 1].location.lng, res.data[res.data.length - 1].location.lat, that.t_lng, that.t_lat);

                if (maxDistance <= 2) {
                  that.tabs[that.xmwzB_index].scale = 12;
                  that.setData({
                    tabs: that.tabs
                  });
                } else if (maxDistance > 2 && maxDistance <= 5) {
                  that.tabs[that.xmwzB_index].scale = 11;
                  that.setData({
                    tabs: that.tabs
                  });
                } else if (maxDistance > 5 && maxDistance <= 20) {
                  that.tabs[that.xmwzB_index].scale = 10;
                  that.setData({
                    tabs: that.tabs
                  });
                } else if (maxDistance > 20 && maxDistance <= 50) {
                  that.tabs[that.xmwzB_index].scale = 9;
                  that.setData({
                    tabs: that.tabs
                  });
                } else if (maxDistance > 50) {
                  that.tabs[that.xmwzB_index].scale = 8;
                  that.setData({
                    tabs: that.tabs
                  });
                } else {
                  that.tabs[that.xmwzB_index].scale = 7;
                  that.setData({
                    tabs: that.tabs
                  });
                }
              }
            } // 只赋值当前tab下的内容，其他tab下的不用管


            var arrlist_key = 'arrlist[' + xmwzB_index + ']';
            that.setData({////设置markers属性，将搜索结果显示在地图中
[arrlist_key]: marks
              markers: marks
            });
            //try fix
            that[arrlist_key] = marks;
          }
        });
      } // 每次切换时，都以自身定位为中心


      let mpCtx = uni.createMapContext("map");
      mpCtx.moveToLocation({
        latitude: this.t_lat,
        longitude: this.t_lng
      });
    },

    // 地图上的气泡点击事件绑定，具体详情可参考微信小程序地图api
    callouttap(e) {
      var that = this;
      var marks = that.markers; // 点击某个tab下的某个气泡，其他气泡恢复为初始状态，点击的气泡变为选中状态
      // 同时把选中的状态的气泡信息存入到location对应位置(给点击跳转导航做准备)

      for (var i = 0; i < marks.length; i++) {
        if (marks[i].callout == undefined) {
          continue;
        }

        marks[i].callout.bgColor = '#ffffff';
        marks[i].callout.color = '#404040';
        marks[i].callout.borderColor = '#8a8a8a';
      }

      that.setData({//['markers[' + that.data.markers.findIndex(n => n.id == e.markerId) + '].callout.bgColor']: '#558ef9'
        //['markers[' + that.data.markers.findIndex(n => n.id == e.markerId) + '].callout.color']: '#ffffff'
        //['markers[' + that.data.markers.findIndex(n => n.id == e.markerId) + '].callout.borderColor']: '#558ef9'
        //['location[' + that.data.xmwzB_index + ']']: that.data.markers[that.data.markers.findIndex(n => n.id == e.markerId)]

        markers: marks,
        navigation: true,
      });
      //try fix
      that['location[' + that.xmwzB_index + ']'] = that.markers[that.markers.findIndex(n => n.id == e.markerId)];
      //try fix
      that['markers[' + that.markers.findIndex(n => n.id == e.markerId) + '].callout.borderColor'] = '#558ef9';
      //try fix
      that['markers[' + that.markers.findIndex(n => n.id == e.markerId) + '].callout.color'] = '#ffffff';
      //try fix
      that['markers[' + that.markers.findIndex(n => n.id == e.markerId) + '].callout.bgColor'] = '#558ef9';
    },

    // 小程序地图api，跳转大地图
    show_big_map: function () {
      var that = this;
      var location_c = that.location[that.xmwzB_index];
      var lat_c = location_c.latitude ? location_c.latitude : '';
      var lng_c = location_c.longitude ? location_c.longitude : '';
      var name_c = location_c.title ? location_c.title : '';
      var address_c = location_c.address ? location_c.address : '';

      if (location_c && lat_c && lng_c && name_c && address_c) {
        uni.getLocation({
          //获取当前经纬度
          type: 'wgs84',
          //返回可以用于wx.openLocation的经纬度，官方提示bug: iOS 6.3.30 type 参数不生效，只会返回 wgs84 类型的坐标信息  
          success: function (res) {
            uni.openLocation({
              //​使用微信内置地图查看位置。
              latitude: lat_c,
              //要去的纬度-地址
              longitude: lng_c,
              //要去的经度-地址
              name: name_c,
              address: address_c
            });
          }
        });
      }
    },

    nav(options) {
      let latitude = parseFloat(util.getValue('latitude', options));
      let longitude = parseFloat(util.getValue('longitude', options));
      let name = util.getValue('name', options);
      let address = util.getValue('address', options);
      uni.openLocation({
        latitude,
        longitude,
        name,
        address
      });
    },

    //计算两点间的距离
    getDistance(lng1, lat1, lng2, lat2) {
      const R = 6371;
      const {
        sin,
        cos,
        asin,
        PI,
        hypot
      } = Math;
      /** 根据经纬度获取点的坐标 */

      let getPoint = (e, n) => {
        e *= PI / 180;
        n *= PI / 180; //这里 R* 被去掉, 相当于先求单位圆上两点的距, 最后会再将这个距离放大 R 倍

        return {
          x: cos(n) * cos(e),
          y: cos(n) * sin(e),
          z: sin(n)
        };
      };

      let a = getPoint(lng1, lat1);
      let b = getPoint(lng2, lat2);
      let c = hypot(a.x - b.x, a.y - b.y, a.z - b.z);
      let r = asin(c / 2) * 2 * R;
      return r;
    }

  }
};
</script>
<style>
/* pages/tools/wangdian/souvenir/souvenir.wxss */
.map_map{
  height: 35vh;
}

/*弹性布局*/
.flex {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  display: box;
  flex-wrap:wrap;
}
.noWarp{
    flex-wrap:nowrap; 
}
/*元素居中*/
.alignC{
  align-items: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -moz-align-items: center;
  -ms-align-items: center;
  -o-align-items: center;
}
/*水平排列*/
.flexH{
  -webkit-box-orient: horizontal;
  -webkit-flex-direction: row;
  -moz-flex-direction: row;
  -ms-flex-direction: row;
  -o-flex-direction: row;
  flex-direction: row;
}
/*垂直排列*/
.flexV {
  -webkit-box-orient: vertical;
  -webkit-flex-direction: column;
  -moz-flex-direction: column;
  -ms-flex-direction: column;
  -o-flex-direction: column;
  flex-direction: column;
}
/*两端对齐*/
.flexSa {
  -webkit-box-pack: justify;
  justify-content: space-around;
  -webkit-justify-content: space-around;
  -moz-justify-content: space-around;
  -ms-justify-content: space-around;
  -o-justify-content: space-around;
}
/*居中对齐*/
.flexC {
  -webkit-box-pack: center;
  justify-content: center;
  -webkit-justify-content: center;
  -moz-justify-content: center;
  -ms-justify-content: center;
  -o-justify-content: center;
}
.flexSb {
  justify-content: space-between;
  -webkit-justify-content: space-between;
  -moz-justify-content: space-between;
  -ms-justify-content: space-between;
  -o-justify-content: space-between;
}
.flexS {
  -webkit-box-pack: start;
  justify-content: flex-start;
  -webkit-justify-content: flex-start;
  -moz-justify-content: flex-start;
  -ms-justify-content: flex-start;
  -o-justify-content: flex-start;
}
.flexE {
  -webkit-box-pack: end;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
  -moz-justify-content: flex-end;
  -ms-justify-content: flex-end;
  -o-justify-content: flex-end;
}
 
.tfLine1 {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
 
/* 页面内容 */
 
.xmwzB{
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: rgba(255, 255, 255, 0.6);
  box-sizing: border-box;
  padding: 20rpx 25rpx;
}
 
.xmwzBLi{
  background-size:48rpx 48rpx;
  background-repeat: no-repeat;
  background-position:top center;
  text-align: center;
  font-size: 30rpx;
  color: #333333;
  padding-bottom: 30rpx;
  position: relative;
}
 
.xmwzBLi:before{
  position: absolute;
  width: 100%;
  height: 10rpx;
  background-color: transparent;
  left: 0;
  bottom: 0;
  display: block;
  content:'';
}
.xmwzBLi.on{
  font-weight: bold;
}
/* .xmwzBLi.on::before{
  background-color: #3072f6;
  color: #3072f6;
} */
.online{
  height: 10rpx;
  background-color: #3072f6;
}
 

 
.xmwzUl{
  padding: 15rpx 0 50rpx;
}
 

 
.xmwzUl-li-name{
  font-size: 30rpx;
  color: #666666;
}
 
.xmwzUl-li-add{
  background-image: url();
  background-size:24rpx 30rpx;
  background-repeat: no-repeat;
  background-position: left center;
  padding-left:36rpx;
  font-size: 30rpx;
  color: #aaaaaa;
}
 
.navigation_btn{
  width:76rpx;
  height:76rpx;
  position: absolute;
  right:30rpx;
  top:50rpx;
}
.body{
  box-sizing: border-box;
  height: 65vh;
  padding-bottom: 115rpx;
  box-shadow: 2px 2px 10px #CCC;
}
.body .box{
  padding: 20rpx 30rpx;
}
.body .box .left .tit{
  font-size: 36rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
}
.body .box .left .intro{
  font-size: 28rpx;
  margin-right: 40rpx;
}
.body .box .right image{
  width: 76rpx;
  height: 76rpx;
}
.fgx{
  height: 8rpx;
}
</style>